<template>
  <t-layout class="layout">
    <div class="batch-container">
      <div class="batch-header">
        <BatchHeader v-model="batchData" :onSubmit="action.submitBatch" />
      </div>
      <div class="batch-content">
        <div class="batch-sidebar">
          <BatchItemList
            v-model="batchData"
            @importItems="action.importItems"
            @deleteItem="action.deleteItem"
            @previewAudio="action.previewAudio"
          />
        </div>
        <div class="batch-main">
          <div class="batch-assignment-area">
            <BatchAssignment
              v-model="batchData"
              :modelSource="state.modelSource"
              @assignAvatar="action.assignAvatar"
              @queryModels="action.queryModels"
              @switchSource="action.switchModelSource"
              :listener="listener"
            />
          </div>
        </div>
      </div>
      <BatchListener ref="listener" />
    </div>
  </t-layout>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import BatchHeader from './header/BatchHeader.vue';
import BatchItemList from './items/BatchItemList.vue';
import BatchAssignment from './assign/BatchAssignment.vue';
import BatchListener from './listener/BatchListener.vue';
import { modelPage, saveVideo, makeVideo, getCommonModelList, makeVideoCommon, findModelCommon } from '@renderer/api'
import { useRoute, useRouter } from 'vue-router'

import { getIP } from '@renderer/api'
import { getAssetPathByKey } from '@renderer/api/assetPaths'

const assetPaths = ref('')

const router = useRouter();
const route = useRoute();

const listener = ref(null);

// 添加状态对象，包含模型源
const state = reactive({
  modelSource: 'common', // 默认使用公共库模型
  loading: false
});

// 使用直接的对象字面量作为默认值
const batchData = defineModel({
  default: () => ({
    name: '批量中英任务',
    contentItems: [], // 文本/音频内容项数组
    models: [], // 数字人模型数组
    assignments: [], // 内容项与数字人的关联数组
  }),
});

const action = {
  // 预览音频 - 增强版本
  previewAudio(data) {
    if (data.action === 'play') {
      const item = data.item;
      if (item && item.type === 'audio' && item.audioUrl) {
        listener.value.listen({
          name: item.name || '未命名',
          audioUrl: item.audioUrl
        });
      }
    } else if (data.action === 'close') {
      listener.value.close();
    }
  },

  // 导入多个内容项（文本或音频）
  importItems(items) {
    // 确保 contentItems 已经初始化
    if (!batchData.value.contentItems) {
      batchData.value.contentItems = [];
    }

    // 直接修改对象属性，确保Vue能检测到变化
    const newContentItems = [...batchData.value.contentItems, ...items];

    // 创建一个新对象以确保Vue能检测到变化
    batchData.value = {
      ...batchData.value,
      contentItems: newContentItems
    };

    // 确保 assignments 已经初始化
    if (!batchData.value.assignments) {
      batchData.value.assignments = [];
    }

    // 为新导入的内容项创建默认关联
    const newAssignments = [...batchData.value.assignments];
    items.forEach(item => {
      newAssignments.push({
        contentId: item.id,
        modelId: null, // 初始时未分配模型
      });
    });

    // 更新 assignments
    batchData.value.assignments = newAssignments;

    // 显示成功提示
    MessagePlugin.success(`成功导入 ${items.length} 个内容项`);

  },

  // 删除单个内容项
  deleteItem(id) {
    const item = batchData.value.contentItems.find(item => item.id === id);

    // 创建新数组以确保Vue能检测到变化
    batchData.value = {
      ...batchData.value,
      contentItems: batchData.value.contentItems.filter(item => item.id !== id),
      assignments: batchData.value.assignments.filter(assignment => assignment.contentId !== id)
    };

    // 显示删除成功提示
    if (item) {
      MessagePlugin.success(`已删除 ${item.name || '未命名'}`);
    }
  },

  // 分配数字人模型到内容项
  assignAvatar(contentId, modelId) {
    // 确保 assignments 已经初始化
    if (!batchData.value.assignments) {
      batchData.value.assignments = [];
    }

    const assignmentIndex = batchData.value.assignments.findIndex(
      assignment => assignment.contentId === contentId
    );

    const newAssignments = [...batchData.value.assignments];

    if (assignmentIndex !== -1) {
      // 更新现有分配关系
      newAssignments[assignmentIndex] = {
        ...newAssignments[assignmentIndex],
        modelId
      };
    } else {
      // 创建新的分配关系
      newAssignments.push({
        contentId,
        modelId,
      });
    }

    // 更新 assignments
    batchData.value = {
      ...batchData.value,
      assignments: newAssignments
    };
  },

  // 添加切换模型源的方法
  async switchModelSource(source) {
    // 如果源没有变化，不需要处理
    if (state.modelSource === source) return;

    state.loading = true;
    try {
      // 更新模型源
      state.modelSource = source;

      // 清空所有分配关系
      if (batchData.value.assignments) {
        batchData.value.assignments = batchData.value.assignments.map(assignment => ({
          ...assignment,
          modelId: null
        }));
      }

      // 清空模型列表
      batchData.value.models = [];

      // 根据不同的源加载对应的模型
      if (source === 'common') {
        await action.queryCommonModels();
        MessagePlugin.success('已切换到公共库模型');
      } else {
        await action.queryModels();
        MessagePlugin.success('已切换到本地模型');
      }

      // 更新URL参数，但不刷新页面
      const newQuery = { ...route.query, common: source === 'common' };
      router.replace({ query: newQuery });

    } catch (error) {
      console.error('切换模型源失败', error);
      MessagePlugin.error('切换模型源失败: ' + error.message);
    } finally {
      state.loading = false;
    }
  },

  // 查询公共库的数字人模型
  async queryCommonModels(searchTerm = '') {
    state.loading = true;
    try {
      const params = {
        page: 1,
        pageSize: 12,
        name: searchTerm
      };

      const result = await getCommonModelList(params);

      if (result && result.data && result.data.records) {
        // 将API返回的数据格式转换为应用所需的格式
        const formattedModels = result.data.records.map(model => ({
          id: model.id,
          name: model.name,
          video_path: `${assetPaths.value}/${model.videoPath}`,
          audio_Path: `${assetPaths.value}/${model.audioPath.replace("\\","/")}`,
          image_path: `${assetPaths.value}/${model.imagePath}`,
          voice_id: model.voiceId,
          isCommonModel: true, // 添加一个标志，标识这是公共库模型
          primaryCategoryId: model.primaryCategoryId,
          secondaryCategoryId: model.secondaryCategoryId,
          tertiaryCategoryId: model.tertiaryCategoryId,
          primaryCategoryName: model.primaryCategoryName,
          secondaryCategoryName: model.secondaryCategoryName,
          tertiaryCategoryName: model.tertiaryCategoryName,
        }));

        // 更新模型列表
        batchData.value = {
          ...batchData.value,
          models: formattedModels
        };
      } else {
        MessagePlugin.warning('未找到公共库数字人模型');
        batchData.value = {
          ...batchData.value,
          models: []
        };
      }
    } catch (error) {
      console.error('查询公共库模型列表失败', error);
      MessagePlugin.error('查询公共库模型列表失败: ' + error.message);
      batchData.value = {
        ...batchData.value,
        models: []
      };
    } finally {
      state.loading = false;
    }
  },

  // 查询本地可用的数字人模型
  async queryModels(searchTerm = '') {
    state.loading = true;
    try {
      const result = await modelPage({
        name: searchTerm,
        page: 1,
        pageSize: 12
      });
      if (result && result.list) {
        // 创建一个新对象以确保Vue能检测到变化
        batchData.value = {
          ...batchData.value,
          models: result.list
        };
      } else {
        MessagePlugin.warning('未找到数字人模型');
        batchData.value = {
          ...batchData.value,
          models: []
        };
      }
    } catch (error) {
      console.error('查询模型列表失败', error);
      MessagePlugin.error('查询模型列表失败: ' + error.message);
      batchData.value = {
        ...batchData.value,
        models: []
      };
    } finally {
      state.loading = false;
    }
  },

  // 提交批量任务
  async submitBatch() {
    try {
      // 检查是否有内容项
      if (!batchData.value.contentItems || batchData.value.contentItems.length === 0) {
        MessagePlugin.warning('请先导入内容');
        return;
      }

      // 检查是否所有内容项都已分配模型
      const unassignedItems = batchData.value.assignments.filter(a => !a.modelId);
      if (unassignedItems.length > 0) {
        MessagePlugin.warning('有内容项尚未分配数字人，请完成分配');
        return;
      }

      // 准备要创建的视频任务
      const successIds = [];

      // 创建成功的计数
      let successCount = 0;
      let failCount = 0;

      // 显示进度提示
      MessagePlugin.loading('正在提交批量任务...');

      // 遍历所有分配关系
      for (const assignment of batchData.value.assignments) {
        // 只处理有模型分配的内容项
        if (!assignment.modelId) continue;

        const contentItem = batchData.value.contentItems.find(item => item.id === assignment.contentId);
        const model = await findModelCommon(assignment.modelId)

        if (!contentItem || !model) continue;

        // 根据内容类型构造视频任务
        try {
          const videoTask = {
            model_id: assignment.modelId,
            name: `${model.name}_${contentItem.name || contentItem.text?.substr(0, 10) || '无标题'}`,
            is_common_model: state.modelSource === 'common'
          };

          // 根据内容类型设置不同的属性
          if (contentItem.type === 'text') {
            videoTask.text_content = contentItem.text;
          } else if (contentItem.type === 'audio') {
            videoTask.audio_path = contentItem.audioUrl;
          }

          // 使用saveVideo API创建视频记录
          const videoId = await saveVideo(videoTask);

          // 记录成功创建的ID，用于后续生成视频
          if (videoId) {
            successIds.push(videoId);
            successCount++;
          }

        } catch (taskError) {
          console.error('创建视频任务失败:', taskError);
          failCount++;
          continue; // 继续处理其它任务
        }
      }

      // 如果有成功创建的视频任务，开始生成视频
      if (successIds.length > 0) {
        // 提示用户生成已开始
        MessagePlugin.success(`成功创建${successCount}个视频任务，开始生成视频`);

        // 逐个触发视频生成
        for (const videoId of successIds) {
          try {
            if (state.modelSource === 'common'){
              await makeVideoCommon(videoId);
            }else {
              await makeVideo(videoId);
            }
          } catch (makeError) {
            console.error(`视频生成失败 (ID: ${videoId}):`, makeError);
          }
        }

        // 再次提示用户
        MessagePlugin.success(`任务已提交，共${successCount}个视频${failCount > 0 ? `，${failCount}个失败` : ''}`);

        // 跳转到首页或其他页面
        setTimeout(() => {
          router.push('/home');
        }, 2000);
      } else {
        MessagePlugin.error('没有成功创建任何视频任务');
      }

    } catch (error) {
      console.error('提交批量任务失败', error);
      MessagePlugin.error('批量任务提交失败：' + (error.message || '未知错误'));
    }
  }
};

onMounted(async () => {
  await getAssetPathByKey('model').then(result => {
    assetPaths.value = result.path_value;
  })

  // 检查是否有common参数，决定加载公共库还是本地模型
  const useLocalModels = route.query.common === 'false' || route.query.common === false;

  // 设置初始模型源
  state.modelSource = useLocalModels ? 'local' : 'common';

  if (state.modelSource === 'local') {
    // 加载本地模型
    await action.queryModels();
  } else {
    // 默认加载公共库模型
    await action.queryCommonModels();
  }

});
</script>

<style lang="less" scoped>
.batch-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  color: #FFFFFF;
  .batch-header {
    height: 60px;
  }

  .batch-content {
    display: flex;
    flex: 1;
    overflow: hidden;
    .batch-sidebar {
      width: 300px;

      overflow: hidden;
    }

    .batch-main {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .batch-assignment-area {
        flex: 1;
        overflow: auto;
        padding: 20px;
      }
    }
  }
}
</style>
